package com.example.listview;



import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
 
public class AllProductsActivity extends Activity {
 
    // Progress Dialog
    private ProgressDialog pDialog;
 
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
 
    ArrayList<Product> productsList;
 
    // url to get all products list
    private static String url_all_products = "http://matrix.umcs.pl/~kwrobel/android_product/get_all_products.php";
 
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "produkty";
    private static final String TAG_PID = "id_produktu";
    private static final String TAG_NAME = "nazwa_produktu";
    private static final String TAG_PODATEK = "podatek";
    private static final String TAG_ID_KATEGORI = "id_kategorii";
 
    // products JSONArray
    JSONArray products = null;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_products);
 
        // Hashmap for ListView
        productsList = new ArrayList<Product>();
 
        // Loading products in Background Thread
        new LoadAllProducts().execute();
 
    }
 
    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }
 
    }
 
    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllProductsActivity.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "POST", params);
 
            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());
 
            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
 
                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);
 
                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);
 
                        // Storing each json item in variable
                        int id = Integer.parseInt(c.getString(TAG_PID));
                        String name = c.getString(TAG_NAME);
                        String podatk = c.getString(TAG_PODATEK);
                        String idkat=c.getString(TAG_ID_KATEGORI);
 
                        productsList.add(new Product(id,name,podatk,idkat));
                        Log.d("com.example.jebaczlodzieji", "Odczytane produkty");
                       
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
            return null;
        }
 
        /**
         * After cxxompleting background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Put Prodact list to menuactivity
                     * */
                	Log.d("com.example.jebaczlodzieji", "new intent");
                    Intent in = new Intent("com.example.jebaczlodzieji.menuActivity");
                    
                    Log.d("com.example.jebaczlodzieji", "new Bundel");
                    Bundle bund = new Bundle();
                    
                    Log.d("com.example.jebaczlodzieji", "put list do bundle");
                    bund.putParcelableArrayList("productList",  productsList);
                    
                    Log.d("com.example.jebaczlodzieji", "put bundle do intent");
                    in.putExtras(bund);
                    
                    Log.d("com.example.jebaczlodzieji", "Zaladowano wszystko i koncze");
                    System.exit(0);
                }
            });
 
        }
 
    }
}